/**
 * Copyright (c) 2020-2024, huli.com
 * All rights reserved.
 */
package com.xiaohujr.xuexue.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Xue Xue (xuexue1@huli.com)
 * // * @version 1.0
 * @since 2020/7/31
 */
public class Q227 {
    public static void main(String[] args) {
//        System.out.println(calculate("3+2+4+5*6*7*8-9"));
//        System.out.println(calculate("42"));
        System.out.println(calculate("1-1+1"));
    }

    public static int calculate(String s) {

        List<String> numslist = Arrays.asList(s.split("\\D+"));
        List<String> opsList = Arrays.asList(s.split("\\d+"));

        if (numslist.size() == 1) {
            return Integer.valueOf(numslist.get(0));
        }
        List<Integer> nums = new ArrayList<>();
        numslist.stream().forEach(a -> {
            if (a != null && !"".equals(a.trim()) && !" ".equals(a)) {
                nums.add(Integer.valueOf(a.trim()));
            }
        });
        List<String> ops = new ArrayList<>();
        opsList.stream().forEach(a -> {
            if (a != null && !"".equals(a.trim()) && !" ".equals(a)) {
                ops.add(a.trim());
            }
        });
        int j = 0;
        int h = 0;
        while (true) {
            if (nums.size() == 0 || ops.size() == 0 || h == ops.size()) {
                break;
            }
            if (nums.size() == 2 || ops.size() == 1) {
                return cal(nums.get(0), nums.get(1), ops.get(0));
            }


            if (ismd(ops.get(h))) {
                int cal = cal(nums.get(j), nums.get(j + 1), ops.get(h));
                nums.set(j, cal);
                nums.remove(j + 1);
                ops.remove(h);
            } else if (!ismd(ops.get(h))) {
                h++;
                j++;
            }
        }
        while (true) {
            int i = 0;
            if (i == nums.size() - 1) {
                break;
            }
            int cal = cal(nums.get(i), nums.get(i + 1), ops.get(i));
            nums.set(i, cal);
            nums.remove(i + 1);
            ops.remove(i);
        }

        return nums.get(0);
    }

    private static boolean ismd(String ch) {
        if ("*".equals(ch) || "/".equals(ch)) {
            return true;
        }
        return false;
    }

    private static int cal(int a, int b, String op) {
        int i = 0;
        switch (op) {
            case "+":
                i = a + b;
                break;
            case "-":
                i = a - b;
                break;
            case "*":
                i = a * b;
                break;
            case "/":
                i = a / b;
                break;
        }
        return i;
    }
}
